package com.mzj.saas.mservice.smartlock.service.huixiangjia;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.saas.repository.pojo.SmartLock;
import com.haixiaoke.saas.repository.service.ISmartLockService;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.mservice.lock.entity.LockAlarm;
import com.mzj.saas.mservice.lock.entity.LockOpenLog;
import com.mzj.saas.mservice.lock.entity.SmartLockAuth;
import com.mzj.saas.mservice.lock.service.LockAlarmService;
import com.mzj.saas.mservice.lock.service.LockOpenLogService;
import com.mzj.saas.mservice.smartlock.vo.DevMacStateVO;
import com.mzj.saas.mservice.smartlock.vo.huixiangjia.HuiXiangJiaCallBackData;
import com.mzj.saas.mservice.smartlock.vo.huixiangjia.HuiXiangJiaLogKeys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author xiaolong
 * @Date 2024/1/31
 **/
@Slf4j
@Service
public class SmartLockHxjEventHandleService {

    private static final String pwdSql = "SELECT a.id,a.user_name as userName  FROM saas_smart_lock_auth a "
            + "LEFT  JOIN  saas_smart_lock_pwd p ON a.id = p.lock_auth_id "
            + "WHERE p.f_authorization_id = ?";

    private static final String cardSql = "SELECT a.id,a.user_name AS userName FROM saas_smart_lock_auth a LEFT JOIN "
            + "saas_smart_lock_card c ON a.id = c.lock_auth_id WHERE c.f_authorization_id  = ?";

    private static final String faceSql = "SELECT a.id,a.user_name AS userName FROM saas_smart_lock_auth a LEFT JOIN "
            + "saas_smart_lock_face f ON a.id = f.lock_auth_id WHERE  f.key_id = ?";

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private LockOpenLogService lockOpenLogService;
    @Autowired
    private ISmartLockService iSmartLockService;
    @Autowired
    private LockAlarmService lockAlarmService;
    @Autowired
    private SmartLockHxjService smartLockHxjService;

    /**
     * 开锁日志回调
     *
     * @param message
     * @return
     */
    public Map<String, Object> lockOpenLog(HuiXiangJiaCallBackData message) {
        Map<String, Object> resultMap = new HashMap<>();
        HuiXiangJiaLogKeys logKeys = message.getLogKeys().get(0);
        if (ObjectUtil.isEmpty(logKeys) || message.getLogType() == null) {
            resultMap.put("code", 500);
            resultMap.put("message", "参数不全");
        }
        try {
            SmartLock smartLock = iSmartLockService.selectBySn(message.getRoomId());
            if (ObjectUtil.isNotEmpty(smartLock)) {
                // 开门记录
                LockOpenLog openLog = new LockOpenLog();
                switch (message.getLogType()) {
                    case 4:   // 开锁
                        switch (logKeys.getKeyType()) {
                            case 2:   // 密码
                                openLog.setOpenMode(0);
                                List<SmartLockAuth> pwdAuth = jdbcTemplate.query(pwdSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), logKeys.getKeyId());
                                if (CollectionUtil.isNotEmpty(pwdAuth)) {
                                    openLog.setUserId(pwdAuth.get(0).getId());
                                    openLog.setOpenUserName(pwdAuth.get(0).getUserName());// 开门人姓名
                                }
                                break;
                            case 4:     // 卡片
                                openLog.setOpenMode(11);
                                List<SmartLockAuth> cardAuth = jdbcTemplate.query(cardSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), logKeys.getKeyId());
                                if (CollectionUtil.isNotEmpty(cardAuth)) {
                                    openLog.setUserId(cardAuth.get(0).getId());
                                    openLog.setOpenUserName(cardAuth.get(0).getUserName());// 开门人姓名
                                }
                                break;
                            case 32:     // 机械钥匙
                                openLog.setOpenMode(30);
                                break;
                            case 128:     // 蓝牙
                            case 129:
                                openLog.setOpenMode(25);
                                break;
                            case 64:    // 人脸
                                openLog.setOpenMode(32);
                                List<SmartLockAuth> faceAuth = jdbcTemplate.query(faceSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), logKeys.getKeyId());
                                if (CollectionUtil.isNotEmpty(faceAuth)) {
                                    openLog.setUserId(faceAuth.get(0).getId());
                                    openLog.setOpenUserName(faceAuth.get(0).getUserName());// 开门人姓名
                                }
                                break;
                        }

                        if (openLog.getOpenMode() != null) {
                            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            openLog.setLockId(smartLock.getId());
                            openLog.setHouseId(smartLock.getHouseId());
                            openLog.setOpenType(1);// 开门类型：0未知 1外开门 2内开门
                            openLog.setBuildName(smartLock.getBuildName());
                            openLog.setCommunityName(smartLock.getCommunityName());
                            openLog.setUnitName(smartLock.getUnitName());
                            openLog.setMatchUserName(smartLock.getMatchUserName());
                            openLog.setRoomNumber(smartLock.getRoomNumber());

                            Long createTime = message.getCreateTime() * 1000;
                            String format = sdf.format(createTime);
                            openLog.setOpenTime(DateUtil.parse(format));
                            openLog.setUserProperty(0);// 开门人性质：0未知 1承租人 2同住人
                            lockOpenLogService.save(openLog);
                        }
                        break;
                    case 1:     // 强拆报警
                    case 2:     // 非法操作报警（错误次数超限等）
                    case 3:     // 低电量报警
                    case 7:     // 胁迫开锁
                        lockWarnLog(message);
                        break;
                }

            }
            resultMap.put("code", 200);
            resultMap.put("message", "success");
        } catch (Exception e) {
            log.error("慧享佳回调数据--开门回调数据异常：{}", e.getMessage(), e);
            resultMap.put("code", 500);
            resultMap.put("message", "系统异常");
        }
        return resultMap;
    }

    /**
     * 锁状态回调
     *
     * @param message
     * @return
     */
    public Map<String, Object> lockStateLog(HuiXiangJiaCallBackData message) {
        Map<String, Object> resultMap = new HashMap<>();
        if (message.getState() == null) {
            resultMap.put("code", 500);
            resultMap.put("message", "参数不全");
        }
        try {
            SmartLock smartLock = iSmartLockService.selectBySn(message.getRoomId());
            if (ObjectUtil.isNotEmpty(smartLock)) {
                switch (message.getState()) {
                    case 3:      // 在线
                        smartLock.setOnlineStatus(1);
                        break;
                    case 4:     // 离线
                        smartLock.setOnlineStatus(0);
                        break;
                }
                ResultBean<DevMacStateVO> lockDetail = smartLockHxjService.getLockDetailInfo(message.getRoomId());
                if (StatusCode.SUCCESS_CODE_10000.getErrorCode() == lockDetail.getCode()) {
                    DevMacStateVO resultData = lockDetail.getResultData();
                    smartLock.setElectricQuantity(resultData.getBattery());
                }
                iSmartLockService.updateById(smartLock);
            }
            resultMap.put("code", 200);
            resultMap.put("message", "success");
        } catch (Exception e) {
            log.error("慧享佳回调数据--锁状态回调异常：{}", e.getMessage(), e);
            resultMap.put("code", 500);
            resultMap.put("message", "系统异常");
        }
        return resultMap;
    }

    /**
     * 锁告警回调
     *
     * @param message
     * @return
     */
    public Map<String, Object> lockWarnLog(HuiXiangJiaCallBackData message) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            SmartLock smartLock = iSmartLockService.selectBySn(message.getRoomId());
            if (ObjectUtil.isNotEmpty(smartLock)) {
                LockAlarm lockAlarm = new LockAlarm();
                switch (message.getLogType()) {
                    case 1:     // 防撬警报
                        lockAlarm.setAlarmType(2);
                        break;
                    case 2:     // 非法操作报警（错误次数超限等）
                        lockAlarm.setAlarmType(4);
                        break;
                    case 3:     // 低压警报
                        lockAlarm.setAlarmType(1);
                        break;
                    case 7:     // 胁迫开锁
                        lockAlarm.setAlarmType(3);
                        break;
                }
                if (lockAlarm.getAlarmType() != null) {
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    lockAlarm.setLockId(smartLock.getId());
                    lockAlarm.setHouseId(smartLock.getHouseId());
                    lockAlarm.setSn(smartLock.getSn());
                    Long createTime = message.getCreateTime() * 1000;
                    String format = sdf.format(createTime);
                    lockAlarm.setAlarmTime(DateUtil.parse(format));
                    ResultBean<DevMacStateVO> lockDetail = smartLockHxjService.getLockDetailInfo(message.getRoomId());
                    if (StatusCode.SUCCESS_CODE_10000.getErrorCode() == lockDetail.getCode()) {
                        DevMacStateVO resultData = lockDetail.getResultData();
                        smartLock.setElectricQuantity(resultData.getBattery());
                        lockAlarm.setElectric(resultData.getBattery());
                    }
                    lockAlarmService.save(lockAlarm);
                    iSmartLockService.updateById(smartLock);
                }
            }
            resultMap.put("code", 200);
            resultMap.put("message", "success");
        } catch (Exception e) {
            log.error("慧享佳回调数据--锁告警回调异常：{}", e.getMessage(), e);
            resultMap.put("code", 500);
            resultMap.put("message", "系统异常");
        }
        return resultMap;
    }
}
